<template>
  <a-modal
    :title="title"
    :width="900"
    :visible="visible"
    :confirm-loading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-form :form="form">
      <a-form-item style="display: none" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-input v-decorator="['id']" />
      </a-form-item>
      <a-form-item label="项目名称" :label-col="labelCol" :wrapper-col="wrapperCol" has-feedback>
        <a-input
          v-decorator="['name', { rules: [{ required: true, message: '请输入项目名称！' }] }]"
          placeholder="请输入项目名称"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { projectAdd, projectEdit } from '@/api/modular/main/project'

export default {
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 }
      },
      title: '',
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this)
    }
  },
  methods: {
    // 新增
    add() {
      this.title = '新增项目'
      this.visible = true
      this.isAdd = true
    },
    // 修改
    edit(record) {
      this.title = '修改项目'
      this.visible = true
      this.isAdd = false
      this.$nextTick(() => {
        this.form.setFieldsValue({
          id: record.id,
          name: record.name
        })
      })
    },

    handleSubmit() {
      const {
        form: { validateFields }
      } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
          const fn = this.isAdd ? projectAdd : projectEdit
          fn(values)
            .then(res => {
              if (res.success) {
                this.$message.success('操作成功')
                this.visible = false
                this.confirmLoading = false
                this.$emit('ok', values)
                this.form.resetFields()
              } else {
                this.$message.error('操作失败：' + res.message)
              }
            })
            .finally(res => {
              this.confirmLoading = false
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.form.resetFields()
      this.visible = false
    }
  }
}
</script>
